package tree.easy;

import tree.TreeNode;

/**
 * 235. 二叉搜索树的最近公共祖先
 */
public class lowestCommonAncestor {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode();
        System.out.println(treeNode.val > 2);
    }

//    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//        int rootVal = root.val,pVal = p.val,qVal = q.val;
//        if (rootVal < pVal && rootVal < qVal)
//            return lowestCommonAncestor(root.right,p,q);
//        if (rootVal > pVal && rootVal > qVal)
//            return lowestCommonAncestor(root.left,p,q);
//        return root;
//    }

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode ans = root;
        while (true) {
            if (ans.val > p.val && ans.val > q.val) {
                ans = ans.left;
            } else if (ans.val < p.val && ans.val < q.val) {
                ans = ans.right;
            } else {
                break;
            }
        }
        return ans;
    }
}
